package cn.jw.starter.game.common.utils;

import java.util.Comparator;
import java.util.List;
import java.util.Optional;

import org.apache.commons.lang3.RandomUtils;

import cn.jw.starter.game.common.utils.model.WeightEntity;
import lombok.extern.slf4j.Slf4j;

/**
 * 根据权重随机某个结果
 *
 * @author wds_prc
 * @since 2024/6/7 22:10
 */
@Slf4j
public class WeightRandomUtil {

    /**
     * 根据权重值，随机出来一个结果值
     * 
     * @param randomByWeights
     * @return
     */

    public static Optional<WeightEntity> randomByWeight(List<WeightEntity> randomByWeights) {
        if (randomByWeights == null || randomByWeights.isEmpty()) {
            log.warn("权重数据为空,无法随机，返回null");
            return Optional.ofNullable(null);
        }
        if (randomByWeights.size() == 1) {
            return Optional.of(randomByWeights.get(0));
        }
        int totalWeight = randomByWeights.stream().mapToInt(c -> c.getValue()).sum();
        if (totalWeight < 0) {
            totalWeight = Integer.MAX_VALUE;
        }
        randomByWeights.sort(Comparator.comparingInt(WeightEntity::getValue));
        int size = randomByWeights.size();
        int randomValue = RandomUtils.nextInt(0, totalWeight);
        WeightEntity first = randomByWeights.get(0);
        if (randomValue < first.getValue()) {
            return Optional.of(first);
        }
        WeightEntity end = randomByWeights.get(randomByWeights.size() - 1);
        if (randomValue >= totalWeight) {
            return Optional.of(end);
        }
        randomValue -= first.getValue();
        WeightEntity result = null;
        for (int i = 1; i < size; i++) {
            WeightEntity randomByWeight = randomByWeights.get(i);
            if (randomValue >= 0 && randomValue < randomByWeight.getValue()) {
                result = randomByWeight;
                break;
            }
            randomValue -= randomByWeight.getValue();
        }
        return Optional.of(result);
    }
}
